package SGUI

import (
	. "SGEngine2"
	"dom4g"
	//"fmt"
)

func GenDockPanelByXml(elem *dom4g.Element, node *Node, tw *TopWidget, p IWidget) IWidget {
	newDockPanel := &DockPanel{}
	newDockPanel.Top = tw
	newDockPanel.Node = node
	parseNodeAttrs(elem, newDockPanel, p)
	return newDockPanel
}

type DockPanel struct {
	WidgetInfo
}

func (this *DockPanel) OnAttach(node *Node) {
	this.Node = node

}

func (this *DockPanel) OnLoad() {
	this.UpdateLayout()
	em := &EventMessage{}
	em.RegisterEvent(EVENT_WIN_RESIZE, this.OnWinReSize)
	this.Node.Add(em)
}

func (this *DockPanel) OnWinReSize(em *EventMessage, x, y int) {
	this.UpdateLayout()
}

func (this *DockPanel) UpdateLayout() {
	offset := this.GetPivotOffset()

	for i := 0; i < this.Node.GetChild().Count(); i++ {
		curNode := this.Node.GetChild().Get(i).(*Node)
		v := curNode.IfGet(IfGetIWidget)
		if v != nil {
			winfo := v.(IWidget).GetWidgetInfo()
			v.(IWidget).OnReSize()
			strDock := winfo.GetAttr("Dock").(string)
			if strDock == "" {
				strDock = "Center"
			}
			this.SetChildDock(v.(IWidget), strDock, offset)
		}
	}
}

/*
    640 X 480
	...............
	.             .
	.             .
	.             .
	...............
*/
func (this *DockPanel) SetChildDock(child IWidget, strDock string, v2 Vec2) {
	dockOffSet := this.GetDockOffSet(strDock)
	winfo := this.GetWidgetInfo()
	SX, SY := winfo.GetSize()
	offsetX, offsetY := float64(SX)*dockOffSet.X, float64(SY)*dockOffSet.Y
	child.GetWidgetInfo().Node.Position = Vec3{offsetX, offsetY, winfo.Node.Position.Z}
}

func (this *DockPanel) GetDockOffSet(strDock string) Vec2 {
	var DockOffset Vec2
	// DockOffset Y
	if strDock == "Top" || strDock == "TopLeft" || strDock == "TopRight" {
		DockOffset.Y = 0.5
	} else if strDock == "Center" || strDock == "Left" || strDock == "Right" {
		DockOffset.Y = 0
	} else {
		DockOffset.Y = -0.5
	}
	//DockOffset X
	if strDock == "TopLeft" || strDock == "Left" || strDock == "BottomLeft" {
		DockOffset.X = -0.5
	} else if strDock == "Center" || strDock == "Top" || strDock == "Bottom" {
		DockOffset.X = 0
	} else {
		DockOffset.X = 0.5
	}
	return DockOffset
}

func (this *DockPanel) GetWidgetInfo() *WidgetInfo {
	return &this.WidgetInfo
}
